import React from "react";
import { type ColumnDef } from "@tanstack/react-table";
import { type VulnerabilityTableData } from "~/types/scanTypes";
import { cn } from "~/components/lib/utils";

// Define a SeverityBadge component for displaying severity levels
export const SeverityBadge = ({ severity }: { severity: string }) => {
  const normalizedSeverity = severity.toUpperCase();

  let bgColor = "bg-blue-100 dark:bg-blue-900/20";
  let textColor = "text-blue-800 dark:text-blue-300";

  if (normalizedSeverity.includes("CRIT")) {
    bgColor = "bg-red-100 dark:bg-red-900/20";
    textColor = "text-red-800 dark:text-red-300";
  } else if (normalizedSeverity.includes("HIGH")) {
    bgColor = "bg-orange-100 dark:bg-orange-900/20";
    textColor = "text-orange-800 dark:text-orange-300";
  } else if (normalizedSeverity.includes("MED")) {
    bgColor = "bg-yellow-100 dark:bg-yellow-900/20";
    textColor = "text-yellow-800 dark:text-yellow-300";
  } else if (normalizedSeverity.includes("LOW")) {
    bgColor = "bg-green-100 dark:bg-green-900/20";
    textColor = "text-green-800 dark:text-green-300";
  }

  return (
    <div
      className={cn(
        "inline-flex rounded-full px-2 py-1 text-xs font-medium",
        bgColor,
        textColor
      )}
    >
      {normalizedSeverity === "CRITICAL"
        ? "Critical"
        : normalizedSeverity === "HIGH"
        ? "High"
        : normalizedSeverity === "MEDIUM"
        ? "Medium"
        : normalizedSeverity === "LOW"
        ? "Low"
        : "Info"}
    </div>
  );
};

// Get severity priority number for sorting (higher priority = higher number)
export const getSeverityPriority = (severity: string): number => {
  const normalizedSeverity = severity.toUpperCase();
  if (normalizedSeverity.includes("CRIT")) return 4;
  if (normalizedSeverity.includes("HIGH")) return 3;
  if (normalizedSeverity.includes("MED")) return 2;
  if (normalizedSeverity.includes("LOW")) return 1;
  return 0;
};

// Column definitions for the scanner vulnerability table
export const scannerVulnerabilityColumns: ColumnDef<
  VulnerabilityTableData,
  any
>[] = [
  {
    accessorKey: "cve",
    header: "CVE ID",
    cell: ({ row }) => (
      <div className="font-mono text-xs font-medium">
        {row.original.cve || "N/A"}
      </div>
    ),
    size: 140,
  },
  {
    accessorKey: "severity",
    header: "Severity",
    cell: ({ row }) => <SeverityBadge severity={row.original.severity} />,
    size: 100,
    sortingFn: (rowA, rowB, columnId) => {
      const severityA = getSeverityPriority(rowA.original.severity);
      const severityB = getSeverityPriority(rowB.original.severity);
      return severityA - severityB; // Default sort high-to-low
    },
  },
  {
    accessorKey: "description",
    header: "Description",
    cell: ({ row }) => (
      <div className="line-clamp-2 max-w-md text-xs">
        {row.original.description || "No description available"}
      </div>
    ),
    size: 400,
  },
  {
    accessorKey: "cvss",
    header: "CVSS",
    cell: ({ row }) => {
      // Ensure cvss is a number and handle potential NaN values
      const rawScore = parseFloat(String(row.original.cvss || 0));
      const score = isNaN(rawScore) ? 0 : rawScore;

      // Determine color based on score
      let color = "bg-blue-500";
      if (score >= 9.0) color = "bg-red-500";
      else if (score >= 7.0) color = "bg-orange-500";
      else if (score >= 4.0) color = "bg-yellow-500";
      else if (score > 0) color = "bg-green-500";

      return (
        <div className="flex items-center">
          <div className="mr-2 text-xs font-medium">{score.toFixed(1)}</div>
          <div className="h-1.5 w-12 rounded-full bg-gray-200 dark:bg-gray-700">
            <div
              className={`h-1.5 rounded-full ${color}`}
              style={{ width: `${Math.min(score * 10, 100)}%` }}
            ></div>
          </div>
        </div>
      );
    },
    size: 100,
    sortingFn: (rowA, rowB, columnId) => {
      const scoreA = parseFloat(String(rowA.original.cvss || 0)) || 0;
      const scoreB = parseFloat(String(rowB.original.cvss || 0)) || 0;
      return scoreB - scoreA; // Default sort high-to-low
    },
  },
  {
    accessorKey: "count",
    header: "Affected Hosts",
    cell: ({ row }) => (
      <div className="text-center font-medium">{row.original.count || 0}</div>
    ),
    size: 120,
  },
];
